# @FileName  : main.py
# @Time      : 2022/4/27 10:18
# @Author    : LuZhaoHui
# @Software  : PyCharm

import cv2

from capUI import Ui_MainWindow
from conf import *
from tool import *

statusLabelLength = (150, 150, 150, 150, 150, 150, 150, 150, 150)
statusImageRotateMsg = ('', '旋转-90', '旋转+90', '旋转180')


# statusTime = QDateTime.currentDateTime()
# capTime = QDateTime.currentMSecsSinceEpoch()


class ocrRun(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(ocrRun, self).__init__(parent)
        self.setupUi(self)
        self.initRedirection()
        self.config = ocrConf('cap.ini')
        self.initVar()
        self.init()
        self.initUI()

    def initRedirection(self):
        self.stdoutbak = sys.stdout
        self.stderrbak = sys.stderr

    def resetRedirection(self):
        sys.stdout = self.stdoutbak
        sys.stderr = self.stderrbak

    def exit(self):
        self.resetRedirection()

    def initVar(self):
        self.start = False
        index = self.config.varConf['CameraIndex']
        self.cap = None
        try:
            self.cap = cv2.VideoCapture(index)
            if not self.cap.isOpened():
                self.cap.release()
                self.cap = None
        except Exception as e:
            print(e)
        # 摄像头
        if self.cap.isOpened():
            print("摄像头 %d 打开" % (index))
        # 定时器：状态定时，图像定时
        self.initStatusLabel()
        self.initStatusTime()
        self.initCameraTime()
        # 解析菜单
        self.actionItems = self.config.varMenu['ActionList'].split(',')
        self.actionTypes = [int(x) for x in self.config.varMenu['ActionType'].split(',')]
        self.actionMarks = [int(x) for x in self.config.varMenu['ActionMark'].split(',')]
        # Zoom
        self.imagePosX = 0
        self.imagePosY = 0
        self.imageZoom = 0
        # 图片大小
        self.imageSize = getImageSize(self.config.varConf['ImageResolution'])
        self.setCameraResolution()

    # 设置状态栏信息
    def initStatusLabel(self):
        self.statusLabel = []
        for i in range(len(statusLabelLength)):
            label = QLabel()
            label.setAlignment(Qt.AlignCenter)
            label.setFixedWidth(statusLabelLength[i])
            self.statusLabel.append(label)
            self.statusBar.addPermanentWidget(self.statusLabel[i], stretch=i)

    # 状态栏显示信息
    def showStatusMsg(self, pos, msg):
        self.statusLabel[pos].setText(msg)

    def flushStatusMsg(self):
        self.showStatusMsg(8, '%d-%d 倍率 %d' % (self.imagePosX, self.imagePosY, self.imageZoom))
        self.showStatusMsg(7, '分辨率 %dx%d' % (self.imageSize[0], self.imageSize[1]))
        self.showStatusMsg(6, '%s' % ('颜色反向' if self.config.varConf['ImageInverse'] else '颜色正向'))
        self.showStatusMsg(5, '%s' % ('垂直翻转' if self.config.varConf['ImageVertical'] else ''))
        self.showStatusMsg(4, '%s' % ('水平翻转' if self.config.varConf['ImageHorizontal'] else ''))
        self.showStatusMsg(3, '%s' % (statusImageRotateMsg[self.config.varConf['ImageRotate']]))
        info = '摄像' if self.cap else '无摄像'
        if self.cap:
            info = '%s:%d,%d' % (info, self.cap.get(cv2.CAP_PROP_FPS), self.cap.get(cv2.CAP_PROP_BUFFERSIZE))
        self.showStatusMsg(2, '%s' % (info))

    # 设置摄像头分辨率
    def setCameraResolution(self):
        if self.cap:
            self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, self.imageSize[0])
            self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, self.imageSize[1])

    # 设置状态栏显示时间
    def initStatusTime(self):
        self.statusTimer = QTimer()
        self.timeLabel = QLabel()
        self.timeLabel.setFixedWidth(200)
        self.statusBar.addPermanentWidget(self.timeLabel, 7)
        self.statusTimer.timeout.connect(self.showStatusTime)
        self.statusTimer.start(1000)

    # 状态栏显示时间
    def showStatusTime(self):
        time = QDateTime.currentDateTime()
        timeDisplay = time.toString('  yyyy-MM-dd  hh:mm:ss  dddd  ')
        self.timeLabel.setText(timeDisplay)
        self.readFrame()

    # 读取一帧图像
    def readFrame(self):
        ret, frame = self.cap.read()
        if ret:
            self.showImage(frame)

    def showImage(self, image):
        height, width, channels = image.shape
        self.showStatusMsg(0, '%d,%d,%d' % (width, height, channels))
        qimg = QImage(image, width, height, QImage.Format_RGB888)
        pix = QPixmap(qimg)
        self.labelImage.setPixmap(pix.scaled(self.labelImage.width(), self.labelImage.height(), Qt.KeepAspectRatio))

    # 设置摄像头刷新时间
    def initCameraTime(self):
        self.cameraFrame = 0.0
        self.capTime = 0
        self.cameraTimer = QTimer()
        self.statusTimer.timeout.connect(self.showCameraTime)
        self.statusTimer.start(self.config.varConf['CameraTime'])

    # 摄像头显示时间
    def showCameraTime(self):
        tv = QDateTime.currentMSecsSinceEpoch()
        if self.capTime:
            self.cameraFrame = 1000.0 / (tv - self.capTime)
            self.showStatusMsg(1, '显示帧率:%6.3f' % (self.cameraFrame))
        self.capTime = tv

    def init(self):
        # 标题栏:Qt.WindowCloseButtonHint
        self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint)
        self.setWindowIcon(QIcon(LOGO))
        self.setWindowTitle(self.config.varConf['Title'])
        self.labelImage.setText('')
        # 0-正常,1-最小,2-最大,9-全屏
        if self.config.varConf['WindowStatus'] == 1:
            self.showMinimized()
        elif self.config.varConf['WindowStatus'] == 2:
            self.showMaximized()
        elif self.config.varConf['WindowStatus'] == 3:
            self.showFullScreen()

    def initUI(self):
        self.flushStatusMsg()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            print('Left mouse button clicked at:', event.pos())
        elif event.button() == Qt.RightButton:
            print('Right mouse button clicked at:', event.pos())

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            print('Left mouse button released at:', event.pos())
        elif event.button() == Qt.RightButton:
            print('Right mouse button released at:', event.pos())

    def mouseMoveEvent(self, event):
        print('Mouse moved to:', event.pos())

    def contextMenuEvent(self, event):
        menu = QMenu(self)
        # ActionList = 全屏, 0, 720P, 1080P, 2K, 4K, 0, 反色, 颜色设置, 0, 放大, 缩小, 局部放大, 0, 垂直翻转, 水平翻转, 0, 不旋转, 旋转 - 90, 旋转 + 90, 旋转180, 0, 关机
        # ActionType = 1, 0, 1, 1, 1, 1, 0, 1, 2, 0, 2, 2, 2, 0, 1, 1, 0, 1, 1, 1, 1, 0, 2
        # ActionMark = 1, 0, 3, 4, 5, 6, 0, 11, 12, 0, 21, 22, 23, 0, 31, 32, 0, 41, 42, 43, 44, 0, 99
        # self.actionItems
        # self.actionTypes
        # self.actionMarks
        #             self.config.writeConf('InputFilePath', path)
        actions = []
        for i, act in enumerate(self.actionItems):
            if act == '0':
                # 间隔线
                actions.append(None)
                menu.addSeparator()
                continue
            # 菜单项目
            actions.append(QAction(act, menu))

            bCheck = False
            bEnable = True

            ires = self.config.varConf['ImageResolution']
            iinv = self.config.varConf['ImageInverse']
            iver = self.config.varConf['ImageVertical']
            ihor = self.config.varConf['ImageHorizontal']
            irot = self.config.varConf['ImageRotate']

            if self.actionMarks[i] == 1:
                if self.config.varConf['WindowStatus'] == 3:
                    bCheck = True
                actions[i].triggered.connect(self.showWindow)
            elif self.actionMarks[i] == 3:
                actions[i].triggered.connect(lambda: self.showImageResolution(0))
                bCheck = (ires == 0)
            elif self.actionMarks[i] == 4:
                actions[i].triggered.connect(lambda: self.showImageResolution(1))
                bCheck = (ires == 1)
            elif self.actionMarks[i] == 5:
                actions[i].triggered.connect(lambda: self.showImageResolution(2))
                bCheck = (ires == 2)
            elif self.actionMarks[i] == 6:
                actions[i].triggered.connect(lambda: self.showImageResolution(3))
                bCheck = (ires == 3)
            elif self.actionMarks[i] == 11:
                actions[i].triggered.connect(self.showImageInverse)
                bCheck = (iinv == 1)
            elif self.actionMarks[i] == 12:
                actions[i].triggered.connect(self.showColorSetup)
            elif self.actionMarks[i] == 21:
                actions[i].triggered.connect(lambda: self.showImageZoom(1))
            elif self.actionMarks[i] == 22:
                actions[i].triggered.connect(lambda: self.showImageZoom(-1))
            elif self.actionMarks[i] == 23:
                actions[i].triggered.connect(self.showImageEnlarge)
            elif self.actionMarks[i] == 31:
                actions[i].triggered.connect(self.showImageVertical)
                bCheck = (iver == 1)
            elif self.actionMarks[i] == 32:
                actions[i].triggered.connect(self.showImageHorizontal)
                bCheck = (ihor == 1)
            elif self.actionMarks[i] == 41:
                actions[i].triggered.connect(lambda: self.showImageRotate(0))
                bCheck = (irot == 0)
            elif self.actionMarks[i] == 42:
                actions[i].triggered.connect(lambda: self.showImageRotate(1))
                bCheck = (irot == 1)
            elif self.actionMarks[i] == 43:
                actions[i].triggered.connect(lambda: self.showImageRotate(2))
                bCheck = (irot == 2)
            elif self.actionMarks[i] == 44:
                actions[i].triggered.connect(lambda: self.showImageRotate(3))
                bCheck = (irot == 3)
            elif self.actionMarks[i] == 99:
                actions[i].triggered.connect(self.closeSystem)

            menu.addAction(actions[i])
            actions[i].setCheckable(True)
            actions[i].setChecked(bCheck)
            actions[i].setEnabled(bEnable)

        # new_action = QAction('打开', menu)
        # new_action.triggered.connect(self.open)
        # close_action = QAction('关闭', menu)
        # close_action.triggered.connect(self.close)
        # new_action.setCheckable(True)
        # close_action.setCheckable(True)
        # menu.addAction(new_action)
        # menu.addSeparator()
        # menu.addAction(close_action)
        # new_action.setChecked(True)
        # close_action.setEnabled(False)
        print('%d %d ' % (len(self.actionItems), len(actions)))
        # point 调用
        menu.exec_(event.globalPos())

    # 设置窗口
    def showWindow(self):
        print('showWindow')
        key = 'WindowStatus'
        value = self.config.varConf[key]
        if value == 2:
            self.showFullScreen()
            value = 3
        else:
            self.showMaximized()
            value = 2
        self.config.varConf[key] = value
        self.config.writeConf(key, value)

    # 分辨率
    def showImageResolution(self, res):
        key = 'ImageResolution'
        print('%s %d' % (key, res))
        value = self.config.varConf[key]
        if value != res:
            value = res
            self.config.varConf[key] = value
            self.config.writeConf(key, value)
            self.imageSize = getImageSize(self.config.varConf[key])
            self.setCameraResolution()
            self.flushStatusMsg()

    # 图像反色
    def showImageInverse(self):
        key = 'ImageInverse'
        value = self.config.varConf[key]
        print('%s %d' % (key, value))
        if value:
            value = 0
        else:
            value = 1
        self.config.varConf[key] = value
        self.config.writeConf(key, value)
        self.flushStatusMsg()

    # 颜色设置
    def showColorSetup(self):
        print('showColorSetup')

    # 放大/缩小
    def showImageZoom(self, zoom):
        self.imageZoom += zoom
        print('showImageZoom %d' % (zoom))
        self.flushStatusMsg()

    # 局部放大
    def showImageEnlarge(self):
        print('showImageEnlarge')

    # 垂直翻转
    def showImageVertical(self):
        key = 'ImageVertical'
        value = self.config.varConf[key]
        print('%s %d' % (key, value))
        if value:
            value = 0
        else:
            value = 1
        self.config.varConf[key] = value
        self.config.writeConf(key, value)
        self.flushStatusMsg()

    # 水平翻转
    def showImageHorizontal(self):
        key = 'ImageHorizontal'
        value = self.config.varConf[key]
        print('%s %d' % (key, value))
        if value:
            value = 0
        else:
            value = 1
        self.config.varConf[key] = value
        self.config.writeConf(key, value)
        self.flushStatusMsg()

    # 图像旋转
    def showImageRotate(self, rot):
        key = 'ImageRotate'
        print('%s %d' % (key, rot))
        value = self.config.varConf[key]
        if value != rot:
            value = rot
            self.config.varConf[key] = value
            self.config.writeConf(key, value)
            self.flushStatusMsg()

    # 关机
    def closeSystem(self):
        print('closeSystem')
        sys.exit(0)


'''

'''

if __name__ == '__main__':
    # 写数据
    app = QApplication(sys.argv)

    main = ocrRun()
    main.show()

    sys.exit(app.exec_())
